package com.yl.ydk.presenter.impl

import android.content.Context
import android.content.Intent
import android.os.CountDownTimer
import com.yl.ydk.R
import com.yl.ydk.api.Api
import com.yl.ydk.base.*
import com.yl.ydk.bean.SendSmsCodeBean
import com.yl.ydk.bean.UserInfoBean
import com.yl.ydk.presenter.contract.BingdingPhoneActivityContract
import com.yl.ydk.ui.activity.CompletedUserInfoActivity
import com.yl.ydk.ui.activity.HomeActivity
import com.yl.ydk.utils.PreferUtil
import com.blankj.utilcode.utils.ToastUtils
import com.google.gson.Gson
import rx.Observer
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers

class BingdingPhoneActivityImpl : BasePresenter<BingdingPhoneActivityContract.View>(),
    BingdingPhoneActivityContract.Presenter<BingdingPhoneActivityContract.View> {


    override fun getLogin(context: Context, vararg query: String?) {
        showLoadingDialog(context)
        addSubscrebe(
            Api.getInstance()?.getLogin(*query)
                ?.observeOn(AndroidSchedulers.mainThread())
                ?.subscribeOn(Schedulers.io())
                ?.unsubscribeOn(Schedulers.io())
                ?.subscribe(object : Observer<UserInfoBean?> {
                    override fun onCompleted() {}
                    override fun onError(e: Throwable) {
                        dismissLoadingDialog()
                        mView?.showError(e.toString())
                    }

                    override fun onNext(t: UserInfoBean?) {
                        dismissLoadingDialog()
                        if (t?.data != null && t.code == 200) {
                            ToastUtils.showLongToastSafe("登录成功...  ")
                            PreferUtil.getInstance().setUserinfo(Gson().toJson(t))
                            PreferUtil.getInstance().phone = t.data.data.phone
                            PreferUtil.getInstance().accessToken = t.data.access_token
                            if (t.data.data.is_completed == 0) {  // 是否已完善信息 0否 1是
                                mView?.getActivity()?.let {
                                    it.startActivityIn(
                                        Intent(
                                            mView?.getActivity(),
                                            CompletedUserInfoActivity::class.java
                                        ), it
                                    )
                                    it.finish()
                                }
                            } else {
                                mView?.getActivity()?.let {
                                    it.startActivityIn(
                                        Intent(
                                            mView?.getActivity(),
                                            HomeActivity::class.java
                                        ), it
                                    )
                                    it.finish()
                                }
                            }
                        } else {
                            mView?.showError(context.getString(R.string.connectFailure))
                        }
                    }
                })
        )
    }

    override fun getSendSmsCode(context: Context, vararg query: String?) {
        showLoadingDialog(context)
        addSubscrebe(
            Api.getInstance()?.getSendSmsCode(*query)
                ?.observeOn(AndroidSchedulers.mainThread())
                ?.subscribeOn(Schedulers.io())
                ?.unsubscribeOn(Schedulers.io())
                ?.subscribe(object : Observer<SendSmsCodeBean?> {
                    override fun onCompleted() {}
                    override fun onError(e: Throwable) {
                        dismissLoadingDialog()
                        mView?.showError(e.toString())
                    }

                    override fun onNext(t: SendSmsCodeBean?) {
                        dismissLoadingDialog()
                        if (t != null && t.code == 200) {
                            ToastUtils.showLongToastSafe("  短信发送成功 请注意接收...  ")
                            startVerifyCodeTimer(60000 + 1050.toLong())
                        } else {
                            mView?.showError(context.getString(R.string.connectFailure))
                        }
                    }
                })
        )
    }

    /**
     * 验证码倒计时开始执行
     *
     * @param millisInFuture 倒计时时间
     */
    private var isCountDown = false
    private var timer: CountDownTimer? = null
    private var timeFinish = 0

    private fun startVerifyCodeTimer(millisInFuture: Long) {
        if (isCountDown) {
            return
        }
        isCountDown = true
        timer = object : CountDownTimer(millisInFuture, 1000) {
            override fun onTick(millisUntilFinished: Long) {
                timeFinish = millisUntilFinished.toInt() / 1000 - 1
                if (timeFinish <= 0) {
                    timeFinish = 0
                }
                mView?.getTvCode()?.text = "$timeFinish s 后重试"
                mView?.getRlCode()?.isClickable = false
            }

            override fun onFinish() {
                isCountDown = false
                mView?.getTvCode()?.text = "获取验证码"
                mView?.getRlCode()?.isClickable = true
            }
        }
        (timer as CountDownTimer).start()
    }

}